package com.hyf.serviceedu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyf.commonutils.JwtUtils;
import com.hyf.commonutils.vo.OrederMember;
import com.hyf.commonutils.fruit;
import com.hyf.serviceedu.client.UcenterClient;
import com.hyf.serviceedu.entity.EduComment;
import com.hyf.serviceedu.service.EduCommentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2022-05-08
 */
@RestController
@RequestMapping("/serviceedu/comment")
//@CrossOrigin
public class EduCommentController {
	
	@Autowired
	private UcenterClient ucenterClient;
	
	@Autowired
	private EduCommentService commentService;
	
	@ApiOperation(value = "添加评论")
	@PostMapping("auth/save")
	public fruit addComment(@RequestBody EduComment eduComment, HttpServletRequest request){
		//根据token获取用户信息
		String memberId = JwtUtils.getMemberIdByJwtToken(request);
		if(StringUtils.isEmpty(memberId)){
			return fruit.error().code(28004).message("请登录");
		}
		eduComment.setMemberId(memberId);
		OrederMember member = ucenterClient.getUcenterById(memberId);
		eduComment.setNickname(member.getNickname());
		eduComment.setAvatar(member.getAvatar());
//        BeanUtils.copyProperties(member,eduComment);
		commentService.save(eduComment);
		return fruit.ok();
	}
	
	//根据课程id查询评论列表
	@ApiOperation(value = "评论分页列表")
	@GetMapping("{page}/{limit}")
	public fruit index(
			@ApiParam(name = "page", value = "当前页码", required = true)
			@PathVariable Long page,
			@ApiParam(name = "limit", value = "每页记录数", required = true)
				   @PathVariable Long limit,
			@ApiParam(name = "courseQuery", value = "查询对象", required = false)
				   String courseId) {
		Page<EduComment> pageParam = new Page<>(page, limit);
		
		QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
		wrapper.eq("course_id",courseId);
		
		commentService.page(pageParam,wrapper);
		List<EduComment> commentList = pageParam.getRecords();
		
		Map<String, Object> map = new HashMap<>();
		map.put("items", commentList);
		map.put("current", pageParam.getCurrent());
		map.put("pages", pageParam.getPages());
		map.put("size", pageParam.getSize());
		map.put("total", pageParam.getTotal());
		map.put("hasNext", pageParam.hasNext());
		map.put("hasPrevious", pageParam.hasPrevious());
		return fruit.ok().data(map);
	}

}

